import VueRouter from 'vue-router';
<template>
	<div class="overflow-hidden">
		<Row>
			<i-col
				span="16"
				style="border-right: 1px solid #ddd"
				class="min-h-screen-md"
			>
				<div class="iconheader flex  end-center px-md">
					<span
						class="b-px flex sa ac w-xl h-xl my-md radius-2xl mx-sm"
					>
						<Icon type="ios-heart-outline" size="25" />
					</span>
					<span
						class="b-px flex sa ac w-xl h-xl my-md radius-2xl mx-sm"
						><Icon type="ios-boat-outline" size="25"
					/></span>
					<span
						class="b-px flex sa ac w-xl h-xl my-md radius-2xl mx-sm"
					>
						<Icon type="ios-expand" size="25"
					/></span>
				</div>
				<div
					class="imgBody flex sa ac h-8/12 w-8/12 text-center mx-auto"
				>
					<img
						:src="nftUriBasePath + nftDetail.uri"
						alt=""
						srcset=""
						class="w-7/12 h-12/12 object-contain"
						v-if="
							nftDetail.uri &&
								nftDetail.uri.length &&
								nftDetail.uri !== 'http://baidu3.com' &&
								/(\.jpeg|\.png|\.jpg|\.gif)$/i.test(
									nftDetail.uri
								)
						"
					/>

					<video
						autoplay
						controls
						muted
						class="w-7/12 h-12/12 object-contain"
						:src="nftUriBasePath + nftDetail.uri"
						v-if="
							nftDetail.uri &&
								nftDetail.uri.length &&
								nftDetail.uri !== 'http://baidu3.com' &&
								/(\.mp4|\.mov|\.rmvb|\.AVI|\.rm|\.FLV)$/i.test(
									nftDetail.uri
								)
						"
					></video>
					<img
						src="../imgs/detail.gif"
						v-if="
							!nftDetail.uri ||
								nftDetail.uri.length == 0 ||
								nftDetail.uri == 'http://baidu3.com'
						"
					/>
				</div>
			</i-col>

			<i-col span="8" class="flex relative h-vh">
				<div class="p-md min-h-5xl w-12/12">
					<div class=" flex sb ac">
						<h2>{{ nftDetail.name }}</h2>

						<div class="flex sa">
							<span
								class="b-px flex sa ac w-xl h-xl my-md radius-2xl mx-sm"
							>
								<Icon type="ios-heart-outline" size="25" />
							</span>
							<span
								class="b-px flex sa ac w-xl h-xl my-md radius-2xl mx-sm"
								><Icon type="ios-boat-outline" size="25"
							/></span>
						</div>
					</div>
					<div>
						<h3>
							{{ forSale(nftDetail.forSale) }}

							<span class="c-gray-500">1 of 1</span>
						</h3>
					</div>

					<h3 class="mh-md">
						{{ fromWeiToHaic(nftDetail.price) }} HAIC
					</h3>
					{{ nftDetail.description }}
					<Tabs
						value="name1"
						class="margin-t h-6/12"
						style="overflow:hidden !important"
					>
						<TabPane label="信息" name="name1">
							<div class="flex start-center">
								<!-- <div>
									<Avatar
										src="https://i.loli.net/2017/08/21/599a521472424.jpg"
									/>
								</div> -->

								<div class="margin">
									<p class="c-gray-500">NFT 地址</p>
									<b>{{ nftContractAddress }}</b>
								</div>
							</div>
							<div
								class="flex ac"
								style="justify-content: flex-start"
							>
								<!-- <div>
									<Avatar
										src="https://i.loli.net/2017/08/21/599a521472424.jpg"
									/>
								</div> -->
								<div class="margin">
									<p class="c-gray-500">NFT ID</p>
									<b>{{ tokenId }}</b>
								</div>
							</div>

							<div class="flex ac start-center">
								<div class="margin">
									<p class="c-gray-500">持有者</p>
									<b>{{ nftDetail.owner }}</b>
								</div>
							</div>
							<div class="flex ac start-center">
								<div class="margin">
									<p class="c-gray-500">资源路径</p>
									<b>{{ nftDetail.uri }}</b>
								</div>
							</div>
						</TabPane>
						<TabPane label="当前竞拍" name="name2">
							<i-form
								label-position="top"
								:label-width="100"
								v-if="
									this.myAddress == nftDetail.owner &&
										nftDetail.forSale
								"
							>
								<FormItem label="竞拍设定">
									<DatePicker
										v-model="bidTime"
										type="datetimerange"
										format="yyyy-MM-dd HH"
										placeholder="设定竞拍开始结束时间"
										style="width: 300px"
									></DatePicker>
								</FormItem>
								<FormItem label="起拍价" :label-width="100">
									<i-input
										type="text"
										v-model="minPrice"
										placeholder="起拍价"
										style="width:300px;"
									/>
								</FormItem>
								<FormItem label="最新最高出价">
									<i-input
										type="text"
										v-model="maxPrice"
										placeholder="最新最高出价"
										disabled
										style="width:300px;"
									/>
								</FormItem>
								<FormItem>
									<Button
										@click.native="createBid"
										shape="circle"
										>提交竞拍设置</Button
									>
								</FormItem>
							</i-form>
							<i-form
								label-position="top"
								:label-width="100"
								v-if="
									this.myAddress != nftDetail.owner &&
										nftDetail.forSale &&
										this.bidStatus == 0
								"
							>
								<FormItem label="竞拍设定">
									<DatePicker
										v-model="bidTime"
										type="datetimerange"
										format="yyyy-MM-dd HH"
										placeholder="设定竞拍开始结束时间2"
										style="width: 300px"
										aria-disabled="true"
									></DatePicker>
								</FormItem>
								<FormItem label="起拍价">
									<i-input
										type="text"
										v-model="minPrice"
										placeholder="起拍价"
										disabled
										style="width:300px;"
									/>
								</FormItem>
								<FormItem
									v-if="nftDetail.forSale"
									label="最新最高出价"
								>
									<i-input
										type="text"
										v-model="maxPrice"
										placeholder="最新最高出价"
										disabled
										style="width:300px;"
									/>
								</FormItem>
								<FormItem
									v-if="this.myAddress != nftDetail.owner"
									label="出价"
								>
									<i-input
										type="text"
										v-model="bidPrice"
										style="width:300px;"
										placeholder="出价"
									/>
								</FormItem>

								<FormItem>
									<Button
										@click.native="submitBid"
										shape="circle"
										v-if="
											this.myAddress != nftDetail.owner &&
												nftDetail.forSale
										"
										>竞拍出价</Button
									>
								</FormItem>
							</i-form>
						</TabPane>

						<TabPane label="中拍记录" name="name3">
							<Table
								stripe
								:columns="columns"
								:data="nftBidDoneList"
							>
								<template slot-scope="{ row }" slot="action">
									<div>
										<Button
											@click="
												buy721(
													row.price,
													row.nft_id,
													true,
													row.id
												)
											"
											v-if="
												myAddress ==
													row.bider_success &&
													nftDetail.forSale &&
													row.pay_status == 0
											"
											>支付
										</Button>
										<p
											v-if="
												nftDetail.forSale &&
													row.pay_status == 1
											"
										>
											已支付
										</p>
										<p
											v-if="
												myAddress !==
													row.bider_success &&
													nftDetail.forSale &&
													row.pay_status == 0
											"
										>
											待支付
										</p>
									</div>
								</template>
							</Table>
						</TabPane>
					</Tabs>
				</div>
				<div
					class="bottomView  h-3/12 my-md absolute bottom-0 text-center w-12/12 py-md"
				>
					<p v-if="this.myAddress == nftDetail.owner">
						价格：<i-input
							type="text"
							v-model="newnftPrice"
							placeholder="请设定nft的价格"
							style="width: 320px"
						/>
					</p>
					<br />
					<p
						v-if="this.myAddress == nftDetail.owner"
						style="padding-left:17px;"
					>
						版税：<i-input
							type="text"
							v-model="royalties"
							placeholder="请设定nft的版税（1-100）"
							style="width: 320px"
						/>

						%
					</p>
					<br />
					<Button
						type="primary"
						@click.native="setSell721"
						shape="circle"
						size="large"
						class="margin"
						style="width:370px;height:60px;"
						v-if="this.myAddress == nftDetail.owner"
						>出售NFT资产</Button
					>
					<Button
						type="primary"
						@click.native="buy721(nftPrice, tokenId)"
						shape="circle"
						style="width:370px;height:60px;"
						size="large"
						class="margin"
						v-if="
							this.myAddress !== nftDetail.owner &&
								nftDetail.forSale &&
								this.bidStatus == 2
						"
						>购买NFT资产</Button
					>
					<p style="text-align: center" class="margin">
						直接购买或者参加竞拍
					</p>
				</div>
			</i-col>
		</Row>
		<Modal v-model="modal" width="300">
			<h1 class="padding">Place a bid</h1>
			<p class="padding">
				You are about to place a bid for CryptoCube#12 by Han
			</p>
			<div class="padding"><b>Your bid</b></div>
			<div></div>
			<p>Your balance</p>
			<h5 class="">0 ETH</h5>
			<div class="flex ac sb padding">
				<p>Your balance</p>
				<h5>0 ETH</h5>
			</div>
			<div class="flex ac sb padding">
				<p>Your balance</p>
				<h5>0 ETH</h5>
			</div>
			<div class="flex ac sb padding">
				<p>Your balance</p>
				<h5>0 HAIC</h5>
			</div>
		</Modal>
	</div>
</template>

<script>
import Web3 from 'web3';

import {
	createNftBid,
	nftBidInfo,
	submitNftBid,
	userLatestBidRecord,
	setnftbidpayed,
	createNftTrade,
} from '@/api';
import { NETWORKID, CONTRACTBUILD, TAXADDRESS, OSSBASEPATH } from '@/config';

export default {
	data() {
		return {
			nftUriBasePath: OSSBASEPATH,
			nftContractAddress: '',
			modal: false,
			value14: '',
			NETWORK_ID: NETWORKID,
			web3: Web3,
			// VRPressToken: '',
			myAddress: '',
			tokenId: 0,
			nftDetail: {},
			nftPrice: 0,
			newnftPrice: 0,
			royalties: 0,
			minPrice: 0,
			bidTime: [],
			bidPrice: 0,
			nft_bid_id: 0,
			bidStatus: 2,
			maxPrice: 0,
			nftBidDoneList: [],
			columns: [
				{
					title: '拍卖No',
					key: 'id',
				},
				{
					title: '中拍者地址',
					key: 'bider_success',
				},
				{
					title: '中拍价',
					key: 'price',
				},
				{
					title: '状态',
					slot: 'action',
					fixed: 'right',
				},
			],
		};
	},
	methods: {
		gotoEdit() {
			this.$router.push('/edit');
		},
		showModal() {
			this.modal = true;
		},
		async setPayed(nftBidId) {
			console.log('pay bid');
			let res = await setnftbidpayed({
				nft_id: this.tokenId,
				nft_bid_id: nftBidId,
				bider_address: this.myAddress,

				lang: 'zh_CN',
			});
			if (res.status == 200) {
				if (res.data.code == 0) {
					console.log('支付回调成功！');
				} else {
					console.log(res.data.msg);
					console.log('支付回调失败！[' + res.data.msg + ']');
				}
			} else {
				console.log('支付回调失败！');
			}
		},

		async submitBid() {
			console.log('create bid');
			let res = await submitNftBid({
				nft_id: this.tokenId,
				nft_bid_id: this.nft_bid_id,
				owner: this.nftDetail.owner,
				bider_address: this.myAddress,
				price: this.bidPrice,

				lang: 'zh_CN',
			});
			if (res.status == 200) {
				if (res.data.code == 0) {
					alert('出价成功！');
				} else {
					console.log(res.data.msg);
					alert('出价失败！[' + res.data.msg + ']');
				}
			} else {
				alert('出价失败！');
			}
		},
		async getBidInfo() {
			//获取当前竞拍设定信息
			let res = await nftBidInfo({
				nft_id: this.tokenId,
				status: 0,
				lang: 'zh_CN',
			});
			if (res.status == 200) {
				if (res.data.code == 0 && res.data.data.length > 0) {
					console.log(JSON.stringify(res.data.data));

					this.minPrice = res.data.data[0].price_min;
					this.bidTime = [
						res.data.data[0].start_time,
						res.data.data[0].end_time,
					];
					this.nft_bid_id = res.data.data[0].id;
					this.bidStatus = res.data.data[0].status;
				}
			}
			//获取该用户出价信息
			let res2 = await userLatestBidRecord({
				nft_id: this.tokenId,
				nft_bid_id: this.nft_bid_id,
				lang: 'zh_CN',
			});
			if (res2.status == 200) {
				if (
					res2.data.code == 0 &&
					res2.data.data.max_price != null &&
					res2.data.data.record != null
				) {
					this.bidPrice = res2.data.data.record.price;
					this.maxPrice = res2.data.data.max_price;
				}
			}

			//获取当前nft中拍记录
			let res3 = await nftBidInfo({
				nft_id: this.tokenId,
				status: 1,
				lang: 'zh_CN',
			});
			if (res3.status == 200) {
				if (res3.data.code == 0) {
					this.nftBidDoneList = res3.data.data;

					// this.nftBidDoneList.some((item) => {
					// 	return item.pay_status == 0;
					// })
					// 	? (this.bidStatus = 1)
					// 	: '';
					for (let i = 0; i < this.nftBidDoneList.length; i++) {
						if (this.nftBidDoneList[i].pay_status == 0) {
							this.bidStatus = 1;
							break;
						}
					}
				}
			}
		},

		async createBid() {
			console.log('create bid');
			let res = await createNftBid({
				nft_id: this.tokenId,
				owner: this.myAddress,
				price_min: this.minPrice,
				start_time: this.rTime(this.bidTime[0]),
				end_time: this.rTime(this.bidTime[1]),
				lang: 'zh_CN',
			});
			if (res.status == 200) {
				if (res.data.code == 0) {
					alert('竞拍创建成功！');
				} else {
					console.log(res.data.msg);
					alert('竞拍创建失败！[' + res.data.msg + ']');
				}
			} else {
				alert('竞拍创建失败！');
			}
		},
		async setSell721() {
			console.log('test detail');
			console.log('my address is' + this.myAddress);

			const contractData = require('../../../' +
				CONTRACTBUILD +
				'/contracts/AssetToken.json');
			const deployData = this.getDeployData();
			// const tokenProxyAdresses = deployData.proxies["marketplace/AssetToken"]
			const VRPressTokenAddress = deployData.contracts.AssetToken.address;
			const marketAddresses = deployData.contracts.Marketplace.address;
			// console.log(VRPressTokenAddress);
			// console.log(marketAddresses);

			const VRPressToken = await new this.web3.eth.Contract(
				contractData.abi,
				// tokenProxyAdresses[tokenProxyAdresses.length - 1].address
				VRPressTokenAddress
			);
			const assetPrice = this.newnftPrice; //todo 需要页面设置价格
			//请求合约发币
			await VRPressToken.methods
				.sellToken(
					marketAddresses,
					this.tokenId,
					this.web3.utils.toWei(assetPrice.toString(), 'ether'),
					this.royalties,
					TAXADDRESS
				)
				.send(
					{
						from: this.myAddress,
						gas: 300000,
					},
					() => {
						console.log('trade in process!');
						alert('上架成功！');
						this.$router.push('/');
					}
				)
				.on('confirmation', () => {
					console.log('complete!');
					// alert("上架成功！");
				})
				.catch(function(error) {
					console.log(error);
				});
		},
		async buy721(buyprice, buynftid, isBid = false, buynftbidid = 0) {
			console.log('test buy');
			console.log(buynftid + '||' + buyprice);
			console.log('my address is' + this.myAddress);

			const contractData = require('../../../' +
				CONTRACTBUILD +
				'/contracts/Marketplace.json');
			const deployData = this.getDeployData();
			// const tokenProxyAdresses = deployData.proxies["marketplace/AssetToken"]
			const VRPressTokenAddress = deployData.contracts.AssetToken.address;
			const marketAddresses = deployData.contracts.Marketplace.address;

			const Marketplace = await new this.web3.eth.Contract(
				contractData.abi,
				marketAddresses
			);
			const assetPrice = buyprice;
			// console.log(Marketplace);
			// console.log(marketAddresses);
			// console.log(this.web3.utils.toWei(assetPrice.toString(), "ether"));
			//请求合约购买
			var buyRlt = 1;
			var buyCallback = await Marketplace.methods
				.transferFrom(VRPressTokenAddress, buynftid)
				.send(
					{
						from: this.myAddress,
						value: this.web3.utils.toWei(
							assetPrice.toString(),
							'ether'
						),
						gas: 300000,
					},
					() => {
						console.log('trading in process');
						alert('购买成功！');
						if (isBid) {
							this.setPayed(buynftbidid);
						}
						this.$router.push('/myhome');
					}
				)
				.on('confirmation', () => {
					console.log('complete');
					// alert("购买成功！");
				})
				.catch(function(error) {
					buyRlt = 0;
					console.log(error);
					alert('购买失败！');
				});
			if (buyRlt) {
				//同步信息到后端接口
				let res4 = await createNftTrade({
					from: this.myAddress,
					to: this.nftDetail.owner,
					nft_address: this.nftContractAddress,
					nft_id: this.tokenId,
					price: buyprice,
					royalties: this.royalties,
					taxAddress: TAXADDRESS,
					txid: buyCallback.transactionHash,
					lang: 'zh_CN',
				});
				if (res4.status == 200) {
					if (res4.data.code !== 0) {
						console.log('同步交易记录失败！');
					}
				} else {
					console.log('同步交易记录失败！');
				}
			}
		},
		async getWeb3() {
			var web3;
			if (window.ethereum) {
				// Modern dapp browsers
				web3 = new Web3(window.ethereum);
				try {
					// metamaskが開いて権限許可を尋ねる
					await window.ethereum.enable();
				} catch (error) {
					// 拒否した場合に入ってくる
					console.log('denied');
				}
			} else if (window.web3) {
				// Legacy dapp browsers...
				web3 = new Web3(window.web3.currentProvider);
			} else {
				// this.selectedModal = this.MODALS.METAMASK
				// this.openModal({
				// 	title: "confirm",
				// 	isOnlyConfirm: true
				// })
			}

			web3 = new Web3(window.web3.currentProvider);
			return web3;
		},
		getDeployData() {
			return require(`../../../zos.dev-${this.NETWORK_ID}.json`);
		},
		forSale(forSale) {
			if (forSale == 1) {
				return '出售中';
			} else {
				return '非卖品';
			}
		},
		fromWeiToHaic(value) {
			return this.web3.utils.fromWei(value, 'ether');
		},
		rTime(date) {
			var json_date = new Date(date).toJSON();
			return new Date(+new Date(json_date) + 8 * 3600 * 1000)
				.toISOString()
				.replace(/T/g, ' ')
				.replace(/\.[\d]{3}Z/, '');
		},
	},
	async mounted() {
		this.web3 = await this.getWeb3();
		await this.web3.eth.getAccounts((error, accounts) => {
			if (error) {
				console.log('error');
				return;
			}
			this.myAddress = accounts[0];
			console.log('my address is' + this.myAddress);
		});
		const contractData = require('../../../' +
			CONTRACTBUILD +
			'/contracts/AssetToken.json');
		const deployData = this.getDeployData();
		const VRPressTokenAddress = deployData.contracts.AssetToken.address;
		console.log(VRPressTokenAddress);
		this.nftContractAddress = VRPressTokenAddress;

		const VRPressToken = await new this.web3.eth.Contract(
			contractData.abi,
			VRPressTokenAddress
		);

		this.tokenId = this.$route.query.nftId;
		this.nftDetail = await VRPressToken.methods
			.getToken(this.tokenId)
			.call();
		this.newnftPrice = this.fromWeiToHaic(this.nftDetail.price);
		this.royalties = this.nftDetail.royalties;
		this.nftPrice = this.fromWeiToHaic(this.nftDetail.price);

		await this.getBidInfo();
		console.log('bidStatus is ;' + this.bidStatus);
	},
};
</script>
